package tk0084.dev.google.quiz.lite;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {

	public static int DEFAULT_TIMEOUT = 120;
	
	/**
	 * @param args
	 * @throws IOException
	 * @throws ClassNotFoundException
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 * @throws InterruptedException
	 */
	public static void main(String[] args) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException, InterruptedException {

		BufferedReader br =  null;
		File file = new File("data.txt");
		if(file.exists()){
			br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
		}else{
			br = new BufferedReader(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream("data.txt")));
		}
		
		String prefix = new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date());
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("target/"+prefix+"-result.txt")));

		String[] header = br.readLine().split(" ");
		final int LX = Integer.parseInt(header[0]);
		final int RX = Integer.parseInt(header[1]);
		final int UX = Integer.parseInt(header[2]);
		final int DX = Integer.parseInt(header[3]);

		int puzzleCount = Integer.parseInt(br.readLine());

		int timeout = DEFAULT_TIMEOUT;
		if(args != null && args.length > 0){
			timeout = Integer.valueOf(args[0]).intValue();
		}
		
		String line = null;
		while ((line = br.readLine()) != null) {
			String[] info = line.split(",");
			if (info.length < 3) {
				continue;
			}

			int col = Integer.parseInt(info[0]);
			int row = Integer.parseInt(info[1]);
			String chars = info[2];

			Puzzle puzzle = new Puzzle(chars, row, col);
			puzzle.setStrategy(new DfsPuzzle());
			puzzle.start();
			boolean interrupted = false;
			try {
				puzzle.join(timeout * 1000);
			} catch (InterruptedException e) {
				System.out.println("interrupted");
				interrupted = true;
			}

			String ans = puzzle.getAnswer();
			if (!interrupted && ans != null && ans.trim().length() > 0) {
				System.out.println(info[3] + "\t" + ans);
				bw.append(info[3] + "\t" + ans);
			} else {
				System.out.println(info[3]);
				bw.append(info[3]);
			}

//			 bw.append(info[3]+"\t"+puzzle.getMd());
			//
			bw.newLine();
			bw.flush();

			// System.gc();
		}
	}

	/**
	 * @param args
	 * @throws IOException
	 * @throws ClassNotFoundException
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 */
	public void read(String[] args) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException {

		BufferedReader br = new BufferedReader(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream("data.txt")));
		String[] header = br.readLine().split(" ");
		final int LX = Integer.parseInt(header[0]);
		final int RX = Integer.parseInt(header[1]);
		final int UX = Integer.parseInt(header[2]);
		final int DX = Integer.parseInt(header[3]);

		int puzzleCount = Integer.parseInt(br.readLine());

		PuzzleEntries puzzleEntries = new PuzzleEntries();

		String line = null;
		int count = 0;
		while ((line = br.readLine()) != null) {
			count++;
			String[] info = line.split(",");
			if (info.length != 3) {
				return;
			}

			int row = Integer.parseInt(info[0]);
			int col = Integer.parseInt(info[1]);
			String chars = info[2];

			Puzzle puzzle = new Puzzle(chars, row, col);
			puzzleEntries.register(count, puzzle.getRow(), puzzle.getCol(), puzzle.getMd(), puzzle.getInitialChars());
		}
	}

	public void exec() throws SQLException {
		PuzzleEntries puzzleEntries = new PuzzleEntries();
		ResultSet rs = puzzleEntries.list();
		while (rs.next()) {
			int puzzleEntryId = rs.getInt("puzzle_entry_id");
			int row = rs.getInt("row");
			int col = rs.getInt("col");
			String puzzleStr = rs.getString("puzzle_string");

			Puzzle puzzle = new Puzzle(puzzleStr, row, col);
			puzzle.setStrategy(new DfsPuzzle());

			System.out.print(puzzleEntryId);
			String ans = puzzle.unpuzzle();
			if (ans.length() > 0) {
				puzzleEntries.answer(puzzleEntryId, ans);
				System.out.println(ans);
			} else {
				System.out.println("");
			}
		}
	}

	class PuzzleEntries {

		PreparedStatement _registerPs;
		PreparedStatement _getPs;
		PreparedStatement _answerPs;
		Connection _connection = DataSource.getConnection();

		PuzzleEntries() {
			try {
				_registerPs = _connection.prepareStatement("insert into puzzle_entry values(?, ? , ?, ?, ?, ?)");
				_getPs = _connection.prepareStatement("select * from puzzle_entry where answer is null order by min_order");
				_answerPs = _connection.prepareStatement("update puzzle_entry set answer = ? where puzzle_entry_id = ?");
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		void answer(int no, String ans) {
			try {
				_answerPs.setString(1, ans);
				_answerPs.setInt(2, no);
				_answerPs.execute();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		void register(int no, int row, int col, int minOrder, String str) {

			try {
				_registerPs.setInt(1, no);
				_registerPs.setInt(2, row);
				_registerPs.setInt(3, col);
				_registerPs.setString(4, str);
				_registerPs.setInt(5, minOrder);
				_registerPs.setString(6, null);

				_registerPs.execute();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		ResultSet list() {
			try {
				return _getPs.executeQuery();
			} catch (SQLException e) {
				e.printStackTrace();
			}

			return null;
		}
	}
}
